package com.yingpai.fitness.dvp_2_0.main.activity.mine;

import android.Manifest;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions2.Permission;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.GsonUtil;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.bean.Dvp_2_1_OrderListBean;
import com.yingpai.fitness.dvp_2_0.main.bean.IsSuccessBean;
import com.yingpai.fitness.dvp_2_0.main.util.DialogUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.dvp_2_0.main.util.sensitive.SensitivewordFilter;
import com.yingpai.fitness.dvp_2_0.main.widget.materialratingbar.MaterialRatingBar;
import com.yingpai.fitness.dvp_2_0.main.widget.round.RCRelativeLayout;
import com.yingpai.fitness.entity.ShopDetailMcipChildBean;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import io.reactivex.functions.Consumer;

/**
 * Created by ASUS on 2018/11/29.
 */

public class CommentActivity extends CommonActivity {
    @BindView(R.id.listview)
    ListView listview;
    private Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX listBean;
    //    private OrderListBean.MapBean.PageInfoBean.ListBean listBean;
    private QuickAdapter<Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean.ListBean> quickAdapter;
    private MaterialRatingBar service_score;
    private MaterialRatingBar logistics_score;
    private MaterialRatingBar describe_score;
    private DecimalFormat df = new DecimalFormat("######.###");
    private List<Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean.ListBean> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.dvp_2_0_activity_comment);

    }

    @Override
    protected void initView() {
        setTitle("发表评价");

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
//            listBean = (OrderListBean.MapBean.PageInfoBean.ListBean) bundle.getSerializable("listBean");
            list = new ArrayList<>();
            listBean = (Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX) bundle.getSerializable("listBean");
            for (int i = 0; i < listBean.getDetailList().size(); i++) {
                list.addAll(listBean.getDetailList().get(i).getList());
            }
        }

        View footView = View.inflate(this, R.layout.comment_foot, null);

        quickAdapter = new QuickAdapter<Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean.ListBean>(this, R.layout.item_shop_comment) {
            @Override
            protected void convert(BaseAdapterHelper helper, final Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean.ListBean item) {
                helper.setText(R.id.title, item.getMerchandiseName());
                helper.setText(R.id.money, "￥" + df.format(item.getSinglePrice() / 100));
                List<ShopDetailMcipChildBean> mcipList = GsonUtil.jsonToList(item.getMcipValue(), ShopDetailMcipChildBean.class);
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < mcipList.size(); i++) {
                    if (i == mcipList.size() - 1) {
                        stringBuilder.append(mcipList.get(i).getPropertyValue());
                    } else {
                        stringBuilder.append(mcipList.get(i).getPropertyValue() + ";");
                    }
                }
                helper.setText(R.id.num_spec, "数量：x" + item.getPurchaseAmount() + ";" + stringBuilder.toString());
                RCRelativeLayout rc_layout = helper.getView(R.id.rc_layout);
                ImageView photo = helper.getView(R.id.photo);
                Glide.with(context)
                        .load(item.getPhotoUrl())
                        .error(R.mipmap.default_small_bg)
                        .into(photo);
                rc_layout.setTopLeftRadius(6);
                rc_layout.setTopRightRadius(6);
                rc_layout.setBottomLeftRadius(6);
                rc_layout.setBottomRightRadius(6);

                final EditText content = helper.getView(R.id.content);
                content.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        SensitivewordFilter filter = new SensitivewordFilter(CommentActivity.this);
                        Set<String> set = filter.getSensitiveWord(content.getText().toString().trim(), 1);
                        if (set.size() > 0) {
                            showToast("您输入的内容包含敏感词");
                        } else {
                            item.setContent(content.getText().toString());
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });

                final LinearLayout take_photo = helper.getView(R.id.take_photo);

                final LinearLayout photo_ll = helper.getView(R.id.photo_ll);

                final TextView photo_num = helper.getView(R.id.photo_num);

                take_photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (rxPermissions.isGranted(Manifest.permission.CAMERA) && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            showTakePhotoOrAlbumDialog(item, take_photo, photo_ll, photo_num);
                        } else {
                            rxPermissions.requestEach(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    .subscribe(new Consumer<Permission>() {
                                        @Override
                                        public void accept(Permission permission) throws Exception {
                                            if (permission.granted) {
                                                // 用户已经同意该权限
                                                showTakePhotoOrAlbumDialog(item, take_photo, photo_ll, photo_num);
                                            } else if (permission.shouldShowRequestPermissionRationale) {
                                                // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                                                showToast("拒绝权限可能导致部分功能不能使用");
                                            } else {
                                                // 用户拒绝了该权限，并且选中『不再询问』
                                                showToast("拒绝权限可能导致部分功能不能使用，如果需要请在设置中修改");
                                            }
                                        }
                                    });
                        }
                    }
                });

            }
        };

        listview.setAdapter(quickAdapter);
        listview.addFooterView(footView);

        quickAdapter.clear();
//        quickAdapter.addAll(listBean.getDetailList());
        quickAdapter.addAll(list);
        quickAdapter.notifyDataSetChanged();

        service_score = footView.findViewById(R.id.service_score);
        logistics_score = footView.findViewById(R.id.logistics_score);
        describe_score = footView.findViewById(R.id.describe_score);

        footView.findViewById(R.id.submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(CommentActivity.this, "发布中...");
                JSONArray jsonArray = new JSONArray();
                HashMap<String, Object> map = new HashMap<>();
                map.put("orderId", listBean.getOrderId());
                for (int i = 0; i < quickAdapter.getCount(); i++) {
                    if (!TextUtils.isEmpty(quickAdapter.getItem(i).getContent()) &&
                            !TextUtils.isEmpty(quickAdapter.getItem(i).getContent().trim())) {
                        map.put("__files" + i, quickAdapter.getItem(i).getImageList());
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("merchandiseId", quickAdapter.getItem(i).getMerchandiseId());
                            jsonObject.put("mcipId", quickAdapter.getItem(i).getMcipId());
                            jsonObject.put("comment", quickAdapter.getItem(i).getContent());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        jsonArray.put(jsonObject);
                    } else {
                        showToast("请填写评价内容");
                        return;
                    }
                }
                map.put("__comments", jsonArray.toString());
                map.put("scores", service_score.getRating() + "," + logistics_score.getRating() + "," + describe_score.getRating());
                comment(map, Url.SHOP_COMMENT);
            }
        });
    }


    private void comment(HashMap<String, Object> map, String url) {
        finalOkGo.requestEncrypt(RequestType.POSTFILESENCRYPT, Contacts.HOST_SERVER + url, map, url, new Callback<IsSuccessBean>() {
            @Override
            public void onSuccess(IsSuccessBean isSuccessBean) {
                if (isSuccessBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                    DialogUtil.getInstance().showCenterDialog(CommentActivity.this, R.layout.dialog_shop_pay_success);
                    DialogUtil.getInstance().dialog_center.setCanceledOnTouchOutside(false);
                    View dialog_center_layout = DialogUtil.getInstance().dialog_center_layout;
                    dialog_center_layout.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            DialogUtil.getInstance().dialog_center.dismiss();
                            EventBus.getDefault().post("3");
                            finishActivity();
                        }
                    });
                    TextView title = dialog_center_layout.findViewById(R.id.title);
                    title.setText("评价成功");
                    TextView message = dialog_center_layout.findViewById(R.id.message);
                    message.setText("感谢您对妖动动的支持！");
                } else {
                    showToast(isSuccessBean.getMessage() + "");
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    @Override
    protected void initData() {

    }


    private void showTakePhotoOrAlbumDialog(final Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean.ListBean listBean, final LinearLayout takePhoto, final LinearLayout photoLl, final TextView photoNum) {
        TDialog tDialog = new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.take_photos_dialog_layout)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.BOTTOM)
                .addOnClickListener(R.id.tv_open_camera, R.id.tv_open_album, R.id.tv_cancel)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.tv_open_camera:
                                FunctionConfig camera = new FunctionConfig.Builder()
                                        .setEnableEdit(true)
                                        .setEnableCrop(true)
                                        .setEnableRotate(true)
                                        .build();
                                //带配置
                                GalleryFinal.openCamera(300, camera, new GalleryFinal.OnHanlderResultCallback() {
                                    @Override
                                    public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                                        if (reqeustCode == 300) {
                                            for (int i = 0; i < resultList.size(); i++) {
                                                if (listBean.getImageList().size() < 3) {
                                                    listBean.getImageList().add(new File(resultList.get(i).getPhotoPath()));
                                                    final View view = View.inflate(context, R.layout.item_refund_image, null);
                                                    view.setTag(listBean.getImageList().get(i));
                                                    photoLl.addView(view);
                                                    ImageView photo = view.findViewById(R.id.photo);
                                                    Glide.with(context)
                                                            .load(resultList.get(i).getPhotoPath())
                                                            .into(photo);
                                                    view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View v) {
                                                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                                            builder.setTitle("温馨提示");
                                                            builder.setMessage("你确定要删除此图片吗?");
                                                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    Log.e("finali", view.getTag() + "");
                                                                    listBean.setPhoto_num(listBean.getPhoto_num() + 1);
                                                                    listBean.getImageList().remove(view.getTag());
                                                                    photoLl.removeView(view);
                                                                    dialog.dismiss();
                                                                    takePhoto.setVisibility(View.VISIBLE);
                                                                    photoNum.setText(listBean.getPhoto_num() + "/" + 3);
                                                                }
                                                            });
                                                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    dialog.dismiss();
                                                                }
                                                            });
                                                            //参数都设置完成了，创建并显示出来
                                                            builder.create().show();
                                                        }
                                                    });
                                                }

                                            }
                                            if (listBean.getImageList().size() == 3) {
                                                takePhoto.setVisibility(View.GONE);
                                            }
                                            listBean.setPhoto_num(listBean.getPhoto_num() - resultList.size());
                                            photoNum.setText(listBean.getPhoto_num() + "/" + 3);
                                        }
                                    }

                                    @Override
                                    public void onHanlderFailure(int requestCode, String errorMsg) {

                                    }
                                });
                                tDialog.dismiss();
                                break;
                            case R.id.tv_open_album:
                                FunctionConfig album = new FunctionConfig.Builder()
                                        .setEnableEdit(true)
                                        .setEnableCrop(true)
                                        .setEnableRotate(true)
                                        .setEnablePreview(true)
                                        .setMutiSelectMaxSize(listBean.getPhoto_num())
                                        .build();
                                //带配置
                                GalleryFinal.openGalleryMuti(200, album, new GalleryFinal.OnHanlderResultCallback() {
                                    @Override
                                    public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                                        if (reqeustCode == 200) {
                                            for (int i = 0; i < resultList.size(); i++) {
                                                if (listBean.getImageList().size() < 3) {
                                                    listBean.getImageList().add(new File(resultList.get(i).getPhotoPath()));
                                                    final View view = View.inflate(context, R.layout.item_refund_image, null);
                                                    view.setTag(listBean.getImageList().get(i));
                                                    photoLl.addView(view);
                                                    ImageView photo = view.findViewById(R.id.photo);
                                                    Glide.with(context)
                                                            .load(resultList.get(i).getPhotoPath())
                                                            .into(photo);
                                                    view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View v) {
                                                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                                            builder.setTitle("温馨提示");
                                                            builder.setMessage("你确定要删除此图片吗?");
                                                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    listBean.setPhoto_num(listBean.getPhoto_num() + 1);
                                                                    Log.e("finali", view.getTag() + "");
                                                                    listBean.getImageList().remove(view.getTag());
                                                                    photoLl.removeView(view);
                                                                    dialog.dismiss();
                                                                    takePhoto.setVisibility(View.VISIBLE);
                                                                    photoNum.setText(listBean.getPhoto_num() + "/" + 3);
                                                                }
                                                            });
                                                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    dialog.dismiss();
                                                                }
                                                            });
                                                            //参数都设置完成了，创建并显示出来
                                                            builder.create().show();
                                                        }
                                                    });
                                                }

                                            }
                                            if (listBean.getImageList().size() == 3) {
                                                takePhoto.setVisibility(View.GONE);
                                            }
                                            listBean.setPhoto_num(listBean.getPhoto_num() - resultList.size());
                                            photoNum.setText(listBean.getPhoto_num() + "/" + 3);
                                        }
                                    }

                                    @Override
                                    public void onHanlderFailure(int requestCode, String errorMsg) {

                                    }
                                });
                                tDialog.dismiss();
                                break;
                            case R.id.tv_cancel:

                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();

    }

    @Override
    @OnClick({})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {

        }
    }
}
